/* *****************************************************************************
 *
 *	danizone.ch
 *
 *	Developer:		mda010
 *	Creation date:	May 6, 2012 9:43:38 PM
 *	
 *	Project name:	HomegrownCuisine
 *	File name:		RecipeService.java
 *
 *	Copyrights (C) 2012 @danizone.ch
 *
 *   This program is free software; you can redistribute it and/or modify
 *	it under the terms of the GNU General Public License as published by
 *	the Free Software Foundation; either version 2 of the License, or
 *	(at your option) any later version.
 *
 *	This program is distributed in the hope that it will be useful,
 *	but WITHOUT ANY WARRANTY; without even the implied warranty of
 *	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 *	GNU General Public License for more details.
 *
 *	Change history:	[developer]; [date];[reason for change]
 *
 *					mda010; May 6, 2012; created
 *
 ***************************************************************************** */
package ch.zhaw.hgc.services.impl;

import java.util.Collections;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import ch.zhaw.hgc.Enumerations.RecipeComparableField;
import ch.zhaw.hgc.Enumerations.SortDirection;
import ch.zhaw.hgc.Utils.Comparators.RecipeComparator;
import ch.zhaw.hgc.daos.IRecipeDao;
import ch.zhaw.hgc.entities.Recipe;
import ch.zhaw.hgc.services.IRecipeService;

import com.google.appengine.api.datastore.Key;

/**
 * Implementation note goes here!
 */
@Service
public class RecipeService implements IRecipeService {

	@Autowired
	private IRecipeDao recipeDao;

	@Override
	@Transactional(readOnly = true)
	public Recipe findByKey(Key key) {

		return recipeDao.findById(key);
	}

	@Override
	@Transactional(readOnly = true)
	public List<Recipe> findAll() {

		return recipeDao.findAll();
	}

	@Override
	@Transactional(readOnly = true)
	public List<Recipe> findAll(String sortableField, String direction) {
		List<Recipe> recipes = recipeDao.findAll();
		if (sortableField != null && !"".equals(sortableField)
				&& direction != null && !"".equals(direction)) {
			RecipeComparator comp = new RecipeComparator();
			RecipeComparableField field = RecipeComparableField
					.valueOf(sortableField);
			SortDirection sortDirection = SortDirection.valueOf(direction);
			comp.setComparableField(field);
			comp.setSortDirection(sortDirection);
			Collections.sort(recipes, comp);
		}
		return recipes;
	}

	@Override
	@Transactional
	public Recipe save(Recipe recipe) {
		if (recipe.getKey() == null) {

			recipe = recipeDao.create(recipe);
		} else {

			recipeDao.update(recipe);
		}

		return recipe;
	}

	@Override
	@Transactional
	public void remove(Recipe recipe) {

		recipeDao.remove(recipe);
	}
}